/**
 * 
 */


var VehicleForm = {
	init: function(){
		var me = this;
		me.initEvent();
		me.initVehicle();
		me.initEnterprise();
		me.initLssuing();
		this.bind();
	},
	initEvent: function(){
		$('.date-alarm-ul li').bind('click',function(i){
			if($(this).index()==0){
				$('.date-alarm').css('left','0px');
				$("#baseInfoDiv").show();
				$("#otherInfoDiv").hide();
			}else{
				$('.line').css('left','100px');
				$("#baseInfoDiv").hide();
				$("#otherInfoDiv").show();
			}
		});
	},
	initEnterprise: function(){
		/*$.ajax({
			url : appCtx + "base/PubDriver/querEnterprise.html",
			type:'post',
			dataType:'json',
			success:function(data){
				$.each(data,function(index,list){
					var option;
					if(enprise==list.entId){
						option="<option value='"+list.entId+"' selected='selected' >"+list.entName+" </option>";
						initCarId();
					}else{
						option="<option value='"+list.entId+"' >"+list.entName+" </option>";
					}
					$("#enprise_id").append(option);
				});
			}
		});*/
		$('#enprise_id').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部业户",
 	        ajax:{
 	            url:appCtx + "/report/alarmSyn/queryEntAndPlatByRole.html?time="+ new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 	          
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部业户"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.entId, "text":obj.entName};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	});
		var enprise = $("#enprise").val();
		if (enprise) {
			$('#enprise_id').val(enprise).trigger("change");
		}
	},
	initVehicle: function(){
    	$("#vehicle_id").select2({
	        theme: "default",
	        allowClear: true,
	        placeholder: "全部车辆",
	        ajax:{
	            url:appCtx + "/base/PubDriver/selectVehicleList.html",
	            dataType:"json",
	            delay:250,
	            data:function(params){
	            	var enterprise = $('#enprise_id').val();
	            	if (isNaN(enterprise)||enterprise==" ") {
	            		enterprise="";
					}
	                return {
	                	enterprise_id:enterprise,
	                	vehicle_no: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部车辆"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
    	                    options.push(option);
	    				});
    	                return {
    	                	results: options,
    	                    pagination: {
    	                        more:false
    	                    }
    	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	    });
    	var ve = $('#vehicle_no').val();
    	if (ve) {
    		$('#vehicle_id').val(ve).trigger("change");
		}
	},
	initLssuing: function(){
		var lssuing = $("#lssuing").val();
		$.ajax({
			url : appCtx + "base/PubDriver/queryOrganzation.html",
			type:'post',
			dataType:'json',
			success:function(data){
				$.each(data,function(index,list){
					var option;
					if(lssuing==list.id){
						option = "<option value='"+list.id+"'  selected='selected'  >"+list.orgn_name+" </option>";
					}else{
						option = "<option value='"+list.id+"' >"+list.orgn_name+" </option>";
					}
					$("#lssuing_auth_id").append(option);
				});
			}
		});
	},
	
	bind : function(){
		$('body').on('click','#addTerminalPanel',function(){
			if ($('#workUnitId').val() == '') {
				showVelidateModal('请选择企业');
				return;
			}
			$("#terminal_UnitID").val($('#workUnitId').val());
			$("#terminal_UnitName").val($('#workUnitId').combotree("getText"));
			$("#terminal_SimNo").focus();
			VehicleForm.initPanel();
			$('.TerminalPanel').show();
			
		});
		
		$('#upPhotoModal .close').click(function(){
			$('#upPhotoModal').hide();
			$('.TerminalPanel').hide();
			return false;
			
		})
		$('body').on('click','#ClearTerminal',function(){
			$("#terminal_SimNo").val('');
			$("#terminal_ComNo").val('');
			$("#terminal_TerminalTypeID").combobox("setValue","");
		});
		
		$("#addTerminal").click(function(){
			VehicleForm.addTerminal()
		});
		
	},
	saveDriver:function(){
		if(action=='update'){
			// 修改从业人员信息
			if(!checkparam()){
				return;
			}
			$.ajax({
				type : 'post',
				url : appCtx + "base/PubDriver/updatePubDriver.html",
				data : $("#vehicleForm").serialize(),
				cache : false,
				dataType : "json",
				success : function(data) {
					if (data.code == "0") {
						global.ajaxLoading.pop('更新成功!',false,800);
						closeDataDialog();
					}else {
						closeDataDialog();
						showVelidateModal("更新失败!");
						return;
					}
				}
			});
		}
		if(action=='save'){
			if(!checkparam()){
				return;
			}
			// 保存从业人员信息
			$.ajax({
				type : 'post',
				url : appCtx + "base/PubDriver/addPubDriver.html",
				data : $("#vehicleForm").serialize(),
				cache : false,
				dataType : "json",
				success : function(data) {
					if (data.code == "0") {
						global.ajaxLoading.pop(data.msg,false,2000);
						closeDataDialog();
					}else {
						global.ajaxLoading.pop(data.msg,false,2000);
						return;
					}
				}
			});
		}
		var funStr = "window.frames['" + mFrameName + "']."+ mDialogCallback;
		eval("(" + funStr + ")");
	}
};

VehicleForm.init();
/**
 * 检查新增从业人员参数
 */
function checkparam(){
	var orgnCode = $("#orgnCode").val();
	var enprise_id = $.trim($("#enprise_id").val());
	var id_card = $("#id_card").val();
	var phone = $("#phone").val();
	var lssuing_auth_id = $("#lssuing_auth_id").val();
	var licence = $("#licence").val();
	var acquire_time = $("#acquire_time").val();
	var grant_time = $("#grant_time").val();
	var invalid_start_time = $("#invalid_start_time").val();
	var invalid_end_time = $("#invalid_end_time").val();
	var status = $("#status").val();
	var driver_licence =$('#driver_licence').val();
	var drive_type = $('#drive_type').val();
	if(orgnCode==null||orgnCode==''){
		global.ajaxLoading.pop('请填写司机姓名',false,1000);
		return false;
	}
	if(enprise_id==null||enprise_id==''){
		global.ajaxLoading.pop('请选择业户',false,1000);
		return false;
	}
	if(id_card==null||id_card==''){
		global.ajaxLoading.pop('请填写身份证号码',false,1000);
		return false;
	}
	if(id_card!=null&&id_card!=''){
		var regsubIdCard=/^[0-9]{18}$/;
		if(!(regsubIdCard.test(id_card))){
			global.ajaxLoading.pop('请填写有效位数身份证号码',false,1000);
			return false;
		}
	}
	if(lssuing_auth_id==null||lssuing_auth_id==''){
		global.ajaxLoading.pop('请选择发证机关',false,1000);
		return false;
	}
	if(driver_licence==null||driver_licence==''){
		global.ajaxLoading.pop('请填写驾驶证',false,1000);
		return false;
	}
	if(drive_type==null||drive_type==''){
		global.ajaxLoading.pop('请选择驾驶类型',false,1000);
		return false;
	}
	if(licence==null||licence==''){
		global.ajaxLoading.pop('请填写从业资格证号',false,1000);
		return false;
	}
	if(acquire_time==null||acquire_time==''){
		global.ajaxLoading.pop('请选择资格证初领时间',false,1000);
		return false;
	}
	if(grant_time==null||grant_time==''){
		global.ajaxLoading.pop('请选择资格证发证时间',false,1000);
		return false;
	}
	if(invalid_start_time==null||invalid_start_time==''){
		global.ajaxLoading.pop('请选择证件有效期开始时间',false,1000);
		return false;
	}
	if(invalid_end_time==null||invalid_end_time==''){
		global.ajaxLoading.pop('请选择证件有效期结束时间',false,1000);
		return false;
	}
	if(status==null||status==''){
		global.ajaxLoading.pop('请选择证照状态',false,1000);
		return false;
	}
	if(phone==null||phone==''){
		global.ajaxLoading.pop('请填写联系人号码',false,1000);
		return false;
	}else{
	    if(!(/^1[34578]\d{9}$/.test(phone))){
	    	global.ajaxLoading.pop('联系人号码格式错误',false,1000);
	        return false; 
	    }
	}
	return true;
}

//打开莫泰框,如果是编辑状态，显示原来的图片
function openPhotoModal(imgID,aUploadID){
	$('#state').val('0');
   var defaulturl=appCtx + "resources/images/touxiang.jpg";
   var img_url=$("#img_url").val();
   if(img_url==null||img_url==''){
	   $("#imgPreviewID").attr("src", defaulturl);
   }else if(img_url!=null&&img_url!=''){
	   $("#imgPreviewID").attr("src", imgPath+'/'+img_url);
   }
	$("#upPhotoModal").show();
	//绑定上传按钮事件
	$('#btnUpload').unbind("click");
	$("#btnUpload").bind("click",function(){uploadImg(imgID,aUploadID)});
	//绑定删除图片按钮事件
	$('#aDeleteImg').unbind("click");
	$("#aDeleteImg").bind("click",function(){deleteImg(imgID,aUploadID)});
}
 //保存关闭上传图片莫泰框
function closePhotoModal(){
	$('#upPhotoModal').hide();
	var url = $("#img_url").val();
	var state = $('#state').val();
	if(state=='1'){
		if(url==yuanimgUrl){
			$("#img_url").val('');
		}
	}
	$("#tbVehicles").flexReload();
}
//删除照片
 function deleteImg(imgID,aUploadID)
 {
 	var defaulturl=appCtx + "resources/images/touxiang.jpg";
 	$("#imgPreviewID").attr("src", defaulturl);
		$("#" + imgID).val("");
		$('#state').val('1');
		$("#"+aUploadID).text("点击上传");
 }
 //上传照片
function uploadImg(imgID,aUploadID) {
	$.ajaxFileUpload({
		url : appCtx + "picture/uploadImg.html",
		fileElementId : "uploadify",
		dataType : 'json',
		data : {
			"fileUploadId" : "uploadify"
		},
		success : function(data, status) {
			var msg = eval("(" + data + ")");
			if (msg.filename != undefined) {
				$("#img_url").val("image/pic/" + msg.filename);
				var url = imgPath + "image/pic/" + msg.filename;
				$("#imgPreviewID").attr("src", url);
				$("#"+imgID).val(url);
			} else if (msg.error == "fileError") {
				$.messager.show({
					title : '系统提示',
					msg : "所选择的文件无效,请重试"
				})
			} else {
				$.messager.show({
					title : '系统提示',
					msg : "上传失败,请重试"
				})
			}
		},
		error : function(data, status, e) {
			$.messager.show({
				title : '系统提示',
				msg : "上传失败,请重试"
			})
		}
	});
}
function prShowStartWait(){
    $("#loading").modal("show");
}
/*  上传图片事件方法结束  */

